import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:village_android/common/NoKeyboardEditableTextFocusNode.dart';
import 'package:village_android/component/jd_button.dart';
import 'package:village_android/config/contants.dart';
import 'package:village_android/config/service_method.dart';
import 'package:village_android/main.dart';
import 'package:village_android/model/dept_model.dart';
import 'package:village_android/model/sys_config_model.dart';
import 'package:village_android/pages/auth/register_first_page.dart';
import 'package:village_android/utils/common_utils.dart';
import 'package:village_android/utils/http_utlis.dart';
import 'package:village_android/utils/store_utils.dart';
import 'dart:convert' as convert;
import 'package:quiver/strings.dart';
class RegisterPage extends StatefulWidget {
  List<SysConfigModel> deptsConfigModelList = [];
  List<SysConfigModel> configModelList = [];

  @override
  _RegisterPageState createState() => new _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  final _formKey = GlobalKey<FormState>();
  Color _eyeColor;
  bool _isClickEye = false;

  String _account;
  String _name;
  String _villageName;
  String _deptId;
  String _deptName = "";
  String _pwd;
  String _upcardURL = "";
  String _downcardURL = "";


  @override
  void initState() {
    super.initState();


    widget.deptsConfigModelList.add(SysConfigModel(name: "第一生产队"));
    widget.configModelList.add(SysConfigModel(name: "村委"));
    getData();
    getConfigData();
  }


  void getData() {
    HttpUtils.get("/sysConfig/list?code=produceTeam",
        data: {}, success: (data) {
          List<SysConfigModel> SysConfigModelM = [];
          if (data != null && (data is List)) {
            for (int i = 0; i < data.length; i++) {
              SysConfigModel model = SysConfigModel.fromJson(data[i]);
              SysConfigModelM.add(model);
            }
          }
          setState(() {
            widget.deptsConfigModelList = SysConfigModelM;
          });
        }, error: (errorMsg) {
          print(errorMsg);
        });
  }
  void getConfigData() {
    HttpUtils.get("/sysConfig/list?code=villageName",
        data: {}, success: (data) {
          List<SysConfigModel> SysConfigModelM = [];
          if (data != null && (data is List)) {
            for (int i = 0; i < data.length; i++) {
              SysConfigModel model = SysConfigModel.fromJson(data[i]);
              SysConfigModelM.add(model);
            }
          }
          setState(() {
            widget.configModelList = SysConfigModelM;
          });
        }, error: (errorMsg) {
          print(errorMsg);
        });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('注册'),
      ),
      body: localWidget(),
      bottomNavigationBar: initBottom(),
    );
  }


  Widget localWidget() {

    return Container(
      padding: EdgeInsets.all(20),
      child: Form(
        key: _formKey,
        child: ListView(
          children: <Widget>[
            SizedBox(height: 10.0),
            initAccount(),
            initLoginName(),
            initLoginPWD(),
            initVillageName(),
            initDeptName(),
            SizedBox(height: 10.0),
            Text(
              "身份证上传【正/反面】",
              style: TextStyle(color: Colors.red),
            ),
            SizedBox(height: 10.0),
            Row(
              children: <Widget>[
                Padding(padding: EdgeInsets.only(left: 10)),
                Expanded(
                  child: initUpCard(),
                ),
                Padding(padding: EdgeInsets.only(left: 15)),
                Expanded(
                  child: initDownCard(),
                ),
                Padding(padding: EdgeInsets.only(right: 10)),
              ],
            ),
            SizedBox(height: 10.0),
            Row(
              children: <Widget>[
                Image.asset("assets/select_red.png",width: 15,height: 15,fit: BoxFit.contain,),
                Padding(padding: EdgeInsets.only(left: 15)),
                Expanded(
                  child: Text("我对以上信息真实性负责，如与村委存档信息不符，将无法注册，具体村委会联系，联系电话02039311982",style: TextStyle(
                    fontSize: 12,
                  ),),
                ),
                Padding(padding: EdgeInsets.only(right: 10)),
              ],
            ),
            SizedBox(height: 50.0),
          ],
        ),
      ),
    );
  }


  Padding initTitle() {
    return Padding(
      padding: EdgeInsets.all(10),
      child: Text(
        '阳光北亭-注册',
        style: TextStyle(
            fontSize: 30.0,
            color: Colors.deepOrange,
            fontWeight: FontWeight.bold),
        textAlign: TextAlign.center,
      ),
    );
  }

  Padding initHorizontalLine() {
    return Padding(
        padding: EdgeInsets.only(top: 10.0, bottom: 10.0),
        child: Align(
          alignment: Alignment.bottomCenter,
          child: Container(
            color: Colors.deepOrange,
            width: 100,
            height: 2,
          ),
        ));
  }

  TextFormField initAccount() {
    return TextFormField(
      onSaved: (String value) => _account = value,
//      maxLength: 11,
      decoration: InputDecoration(labelText: '11位手机号'),
//      validator: (String value) {
//        var isPhone = RegExp("^1[3456789][0-9]{9}");
//        if (!isPhone.hasMatch(value)) {
//          return '手机号格式不正确';
//        }
//      },
    );
  }

  TextFormField initLoginName() {
    return TextFormField(
      onSaved: (String value) => _name = value,
      decoration: InputDecoration(labelText: '真实姓名(不可修改)',hintText: "请输入姓名"),
//      validator: (String value) {
//        if (value == '') {
//          return '真实姓名不能为空';
//        }
//      },
    );
  }

//  TextFormField initVillageName() {
//    return TextFormField(
//      onSaved: (String value) => _villageName = value,
//      decoration: InputDecoration(labelText: '户代表'),
////      validator: (String value) {
////        if (value == '') {
////          return '户代表不能为空';
////        }
////      },
//    );
//  }
  TextField initVillageName() {
    return TextField(
      controller: TextEditingController()..text = _villageName,
      focusNode: NoKeyboardEditableTextFocusNode(),
      onTap: (() {
        showVillageNameAlertDialog();
      }),
      decoration: new InputDecoration(labelText: '身份属性', hintText: '点击选择'),
      onChanged: (value) {
        _deptName = value;
      },
    );
  }

  TextField initDeptName() {
    return TextField(
      controller: TextEditingController()..text = _deptName,
      focusNode: NoKeyboardEditableTextFocusNode(),
      onTap: (() {
        showDeptAlertDialog();
      }),
      decoration: new InputDecoration(labelText: '所属生产队', hintText: '点击选择'),
      onChanged: (value) {
        _deptName = value;
      },
    );
  }

  TextFormField initLoginPWD() {
    return TextFormField(
      obscureText: _isClickEye,
      onSaved: (String value) => _pwd = value,
//      validator: (String value) {
//        if (value.isEmpty) {
//          return '密码不能为空';
//        }
//      },
      decoration: InputDecoration(
        labelText: '密码',
        suffixIcon: IconButton(
            icon: Icon(Icons.remove_red_eye, color: _eyeColor),
            onPressed: () {
              setState(() {
                _isClickEye = !_isClickEye;
                _eyeColor = _isClickEye ? Colors.grey : Colors.blue;
              });
            }),
      ),
    );
  }
  Widget initUpCard() {
    return GestureDetector(
        child: Container(
//          color: Colors.black12,
          height: 150,
          decoration: BoxDecoration(
            image: DecorationImage(
              image: NetworkImage(kImageHost + 'upload_asset.png'),
              fit: BoxFit.contain,
            ),
          ),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(10),
            child: Image.network(
              _upcardURL,
              height: 100,
              width: 100,
              fit: BoxFit.fill,
            ),
          ),
        ),
        onTap: (() {
          _openGallery("upcardURL");
        }));
  }
  Widget initDownCard() {
    return GestureDetector(
        child: Container(
//          color: Colors.black12,
          height: 150,
          decoration: BoxDecoration(
            image: DecorationImage(
              image: NetworkImage(kImageHost + 'upload_asset.png'),
              fit: BoxFit.contain,
            ),
          ),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(10),
            child: Image.network(
              _downcardURL,
              height: 100,
              width: 100,
              fit: BoxFit.contain,
            ),
          ),
        ),
        onTap: (() {
          _openGallery("downcardURL");
        }));
  }

  // 上传图片
  _openGallery(field) async {
    var imgfile = await ImagePicker.pickImage(source: ImageSource.gallery,imageQuality: 10);
    String path = imgfile.path;
    var name = path.substring(path.lastIndexOf("/") + 1, path.length);
    FormData formData =
    new FormData.from({"file": new UploadFileInfo(new File(path), name)});

    HttpUtils.postForm("/api/file/upload", formData: formData,context: context, success: (data) {
      CommonUtils.showToast(context, "上传成功");
      setState(() {
        var src = data["src"];
         if (field == "upcardURL") {
          _upcardURL = src;
        }else if (field == "downcardURL") {
          _downcardURL = src;
        }
      });
    }, error: (errorMsg) {
      CommonUtils.showToast(context, errorMsg);
    });
  }


  Widget initBottom() {
    return BottomAppBar(
        child: Row(
          children: <Widget>[
            Expanded(
                child: JdButton(
                  callBack: () {
                    //CommonUtils.showToast(context, '登录');
                    if (_formKey.currentState.validate()) {
                      _formKey.currentState.save();
                      showAlertDialog();
                    }
                  },
                  text: "注册",
                  color: Colors.red,
                )),
          ],
        ));
  }

  List<Widget> getVillageRadioList() {
    List<RadioListTile<SysConfigModel>> radioList = [];
    SysConfigModel _newValue = null;
    for (int i = 0; i < widget.configModelList.length; i++) {
      SysConfigModel model = widget.configModelList[i];
      RadioListTile listTile = RadioListTile<SysConfigModel>(
        value: model,
        title: Text(model.name),
        groupValue: _newValue,
        onChanged: (value) {
          SysConfigModel newModel = value;
          setState(() {
            _villageName = newModel.name;
          });
          Navigator.of(context).pop();
        },
      );
      radioList.add(listTile);
    }
    return radioList;
  }

  List<Widget> getRadioList() {
    List<RadioListTile<SysConfigModel>> radioList = [];
    SysConfigModel _newValue = null;
    for (int i = 0; i < widget.deptsConfigModelList.length; i++) {
      SysConfigModel model = widget.deptsConfigModelList[i];
      RadioListTile listTile = RadioListTile<SysConfigModel>(
        value: model,
        title: Text(model.name),
        groupValue: _newValue,
        onChanged: (value) {
          SysConfigModel newModel = value;
          setState(() {
            _deptId = newModel.value.toString();
            _deptName = newModel.name;
          });
//          _deptId = value;

          Navigator.of(context).pop();
        },
      );
      radioList.add(listTile);
    }
    return radioList;
  }

  void showDeptAlertDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return new SimpleDialog(
          title: new Text('选择生产队/部门'),
          children: getRadioList(),
        );
      },
    ).then((val) {});
  }
  void showVillageNameAlertDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return new SimpleDialog(
          title: new Text('选择身份属性'),
          children: getVillageRadioList(),
        );
      },
    ).then((val) {});
  }

  void showAlertDialog() {


    if(isEmpty(_account)){
      CommonUtils.showToast(context, "请填写手机");
      return;
    }
    if(isEmpty(_name)){
      CommonUtils.showToast(context, "请填写名字");
      return;
    }
    if(isEmpty(_account)){
      CommonUtils.showToast(context, "请填写手机");
      return;
    }
    if(isEmpty(_pwd)){
      CommonUtils.showToast(context, "请填写密码");
      return;

    }
    if(isEmpty(_villageName)){
      CommonUtils.showToast(context, "请填写户代表");
      return;

    }
    if(isEmpty(_deptId)){
      CommonUtils.showToast(context, "请选择生产队/部门");
      return;

    }

    if(isEmpty(_upcardURL) || isEmpty(_downcardURL)){
      CommonUtils.showToast(context, "请上传身份证");
      return;

    }

    showDialog(
        context: context,
        builder: (_) => new AlertDialog(
                title: new Text("是否注册"),
                content: new Text(""),
                actions: <Widget>[
                  new FlatButton(
                    child: new Text("取消"),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                  new FlatButton(
                    child: new Text("确定"),
                    onPressed: () {
                      Navigator.of(context).pop();
                      toDone();
                    },
                  )
                ]));
  }

  Future toDone() async {


    FormData formData = new FormData.from({
      "account": _account,
      "phone": _account,
      "name": _name,
      "password": _pwd,
      "rePassword": _pwd,
      "villageName": _villageName,
      "deptId": _deptId,
      "upcardURL": _upcardURL,
      "downcardURL": _downcardURL,
    });
//    var dio = new Dio();
//    var response =
//        await dio.post(BaseUrl.url + "/mgr/register", data: formData);
//    print(response.data.toString());
//
//    var data = response.data;

    HttpUtils.postForm("/mgr/register", formData: formData, success: (data) {
      CommonUtils.showToast(context, "注册成功,请登录");
      new Future.delayed(
          const Duration(seconds: 1),
          () => {
                Navigator.of(context).pushNamedAndRemoveUntil(
                    "/login", ModalRoute.withName("/login"))
              });
    }, error: (errorMsg) {
      CommonUtils.showToast(context, errorMsg);
    });
  }
}
